﻿@using CleanArchitecture.Core.Helper
@using CleanArchitecture.Infrastructure.Models.AdminUsers
@using System.Text.RegularExpressions
@model AdminUserModel
@{
    Layout = "_BackendLayout";
    ViewData["Title"] = ViewBag.PageTitle as string;
    var displayMobile = string.IsNullOrEmpty(Model.Mobile)
                      ? ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.Mobile)
                      : Regex.Replace(Model.Mobile, "(\\d{3})\\d{4}(\\d{4})", "$1 **** $2");
    var displayEmail = string.IsNullOrEmpty(Model.Email)
                      ? ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.Email)
                      : Regex.Replace(Model.Email, @"(?<=\S\S*?)[^@\s](?=\S*?@\S+)", "*");
    int PwdMinLen = ViewBag.PasswordMinLen;
    int PwdMaxLen = ViewBag.PasswordMaxLen;
}
@section cssstyles{
    <style type="text/css">
        .user-info-head img {
            width: 110px;
            height: 110px;
            border-radius: 50%;
        }

        .info-list-item {
            position: relative;
            padding-bottom: 8px;
        }

            .info-list-item i {
                float: left;
            }

            .info-list-item > p {
                margin-left: 30px;
            }

        .dash {
            border-bottom: 1px dashed #ccc;
            margin: 15px 0;
        }

        .layui-form-switch {
            margin-top: 6px;
            height: 25px;
        }

        xm-select .scroll-body {
            width: 500px;
            padding-left: 10px;
            overflow: hidden;
        }
    </style>
}
<div class="layui-fluid">
    <div class="layui-form layui-row layui-col-space15">
        <!-- 左 -->
        <div class="layui-col-sm12 layui-col-md3">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 25px;">
                    <div class="text-center layui-text">
                        <div class="user-info-head" id="imgHead">
                            <img alt="用户头像">
                        </div>
                        <h2 style="padding-top: 20px;">@(string.IsNullOrEmpty(Model.UserName) ? ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.UserName) : Model.UserName)</h2>
                        <p style="padding-top: 8px;">@displayEmail</p>
                        <p style="padding-top: 8px;">@displayMobile</p>
                    </div>
                    <div class="layui-text" style="padding-top: 30px;">
                        <div class="info-list-item">
                            <i class="layui-icon layui-icon-username"></i>
                            <p>@(string.IsNullOrEmpty(Model.UserLoginName) ? ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.UserLoginName) : Model.UserLoginName)</p>
                        </div>
                        <div class="info-list-item">
                            <i class="layui-icon layui-icon-time"></i>
                            <p>@(Model.LastLoginTime == null ? ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.LastLoginTime) : Model.LastLoginTime.ToString("yyyy-MM-dd HH:mm"))</p>
                        </div>
                        <div class="info-list-item">
                            <i class="layui-icon layui-icon-location"></i>
                            <p>@(string.IsNullOrEmpty(Model.LastLoginIpAddress) ? ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.LastLoginIpAddress) : Model.LastLoginIpAddress)</p>
                        </div>
                    </div>
                    <div class="dash"></div>
                    <h3>@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.AvailableAdminRoles))</h3>
                    <div class="layui-badge-list" style="padding-top: 6px;">
                        @foreach (var role in Model.AvailableAdminRoles)
                        {
                            <div class="layui-hide userRoledatas" data-rolename="@role.Text" data-roleid="@role.Value" data-check="@(role.Selected ? "check" : "uncheck")"></div>
                        }
                        @*<ul class="checkBox"></ul>*@
                        <div id="transferSelect" style="width: 100%;"></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 右 -->
        <div class="layui-col-sm12 layui-col-md9">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="user-info-form layui-text" style="max-width: 800px;padding-top: 25px;">
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.Email))</label>
                            <div class="layui-input-inline">
                                <input type="text" name="@Model.nameof(m => m.Email)" value="@Model.Email" lay-verify="required|email" placeholder="请输入Email" autocomplete="off" class="layui-input" />
                            </div>
                            @if (string.IsNullOrEmpty(Model.Email))
                            {//新用户注册
                                <div class="layui-form-mid layui-word-aux">Email可用于账号登录，需保证唯一性</div>
                            }
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.Mobile))</label>
                            <div class="layui-input-inline">
                                <input type="text" name="@Model.nameof(m => m.Mobile)" value="@Model.Mobile" lay-verify="required|phone" placeholder="请输入手机号码" autocomplete="off" class="layui-input" />
                            </div>
                            @if (string.IsNullOrEmpty(Model.Mobile))
                            {//新用户注册
                                <div class="layui-form-mid layui-word-aux">手机号可用于账号登录，需保证唯一性</div>
                            }
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.UserLoginName))</label>
                            <div class="layui-input-inline">
                                <input type="text" name="@Model.nameof(m => m.UserLoginName)" value="@Model.UserLoginName" lay-verify="required" placeholder="请输入登录账号" autocomplete="off" class="layui-input" />
                            </div>
                            @if (string.IsNullOrEmpty(Model.UserLoginName))
                            {//新用户注册
                                <div class="layui-form-mid layui-word-aux">账号登录需保证唯一性，以字母开头的字母数字组合，且长度为3-20位</div>
                            }
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.UserName))</label>
                            <div class="layui-input-inline">
                                <input type="text" name="@Model.nameof(m => m.UserName)" value="@Model.UserName" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input" />
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.NewPassword))</label>
                            <div class="layui-input-inline">
                                <input type="password" name="@Model.nameof(m => m.NewPassword)" value="@Model.NewPassword" @if (Model.Id == 0) { <text> lay-verify="required" </text> } placeholder="请输入账户密码" autocomplete="off" class="layui-input" />
                                <input type="text" class="layui-hide" name="@Model.nameof(m => m.PasswordStrongLevel)" value="@Model.PasswordStrongLevel" />
                            </div>
                            <div class="layui-form-mid layui-word-aux">新密码应在 @PwdMinLen - @PwdMaxLen 位之间</div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdminUserModel>(m => m.IsActive))</label>
                            <div class="layui-input-block">
                                <input type="checkbox" name="@Model.nameof(m => m.IsActive)" value="@Model.IsActive" lay-filter="IsActiveSwitch" lay-skin="switch" lay-text="正常|锁定" @if (Model.IsActive == CleanArchitecture.Infrastructure.Entities.EntityEnumConfig.LockState.Active) { <text> checked</text> }>
                            </div>
                        </div>
                        <input type="text" name="@Model.nameof(m => m.Id)" value="@Model.Id" class="layui-hide" />
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button type="button" class="layui-btn" lay-filter="userInfoSubmit" lay-submit="">
                                    保存提交
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section scripts{
    <script src="~/lib/xm-select/dist/xm-select.js" asp-append-version="true"></script>
    <script type="text/javascript">
        layui.use(['layer', 'form', 'element', 'notice', 'transfer'], function () {
            var form = layui.form,
                element = layui.element,
                layer = layui.layer,
                notice = Util.notice !== null && Util.notice() !== null
                    ? Util.notice() : layui.notice,
                transfer = layui.transfer,
                lodash = _;
            //用户头像设置
            var userImageUrl = "@Model.FaceImageUrl",
                srcArr = null;
            if (userImageUrl !== "") {
                srcArr = lodash.split(userImageUrl, ';', 2);
                $("#imgHead img").attr('src',srcArr[1]);
            }

            var userRoleSelecter = null;
            let initRoleCheckbox = function () {
                let nodes = [],
                    userRoleIds = [];
                $("div.userRoledatas").each(function () {
                    let othis = $(this),
                        isChecked = othis.data("check") === "check" ? true : false;
                    let checknode = {
                        value: othis.data("roleid"),
                        title: othis.data("rolename"),
                        disabled: false,
                        checked: isChecked
                    };
                    nodes.push(checknode);
                    //othis = $(this);
                    //checknode.dataid = othis.data("roleid");
                    //checknode.title = othis.data("rolename");
                    //checknode.on = othis.data("check") === "check" ? true : false;
                    if (isChecked) userRoleIds.push(othis.data("roleid"));
                });
                //checkbox({
                //    elem: ".layui-badge-list ul.checkBox"
                //    , nodes: nodes
                //    , click: function (node) {
                //        //console.log("点击", node);
                //    }
                //});
                userRoleSelecter = xmSelect.render({
                    el: '#transferSelect',
                    content: "<div id='transfer'></div>",
                    height: 'auto',
                    autoRow: true,
                    theme: {
                        color: '#0081ff',
                    },
                    initValue: userRoleIds,
                    data: nodes,
                    prop: { name: 'title' },
                    on: function (data) {
                        if (!data.isAdd) {
                            transfer.reload('transfer', {
                                value: userRoleSelecter.getValue('value')
                            })
                        }
                    }
                });

                transfer.render({
                    id: 'transfer',
                    elem: '#transfer',  //绑定元素
                    title: ['所有角色', '已选角色'],
                    data: nodes,
                    value: userRoleIds,
                    onchange: function (data, index) {
                        if (index == 0) {
                            userRoleSelecter.append(data)
                        } else {
                            userRoleSelecter.delete(data)
                        }
                    }
                });
            };
            initRoleCheckbox();
            let NewPwdMod = 0, //新密码强度校验
                $StrongLevel = $("input[name='PasswordStrongLevel']");
            $("input[name='NewPassword']").on('blur', function () {
                if ($(this).val().trim() === "") return false;
                let PwdMinLen = @PwdMinLen,
                    PwdMaxLen = @PwdMaxLen;

                NewPwdMod = Util.checkPasswordStrong($(this).val(), PwdMinLen, PwdMaxLen);
                let strong = "当前密码强度：";
                if (NewPwdMod > 0 && NewPwdMod < 2) {
                    strong += "低";
                    $StrongLevel.val("1"); //与后台数据库对应
                }
                else if (NewPwdMod >= 2 && NewPwdMod < 4) {
                    strong += "中";
                    $StrongLevel.val("2");
                }
                else if (NewPwdMod >= 4) {
                    strong += "强";
                    $StrongLevel.val("3");
                }
                else strong = "密码长度超出限定范围"; //returns 0 密码过长或过短
                layer.tips(strong, $(this), { tips: 1 });
            });
            //更新用户状态
            form.on('switch(IsActiveSwitch)', function (data) {
                $(data.elem).val((data.elem.checked) ? "1" : "0");
                form.render('checkbox');
            });

            form.on('submit(userInfoSubmit)', function (data) {
                var postData = data.field;
                if ((NewPwdMod <= 0 && postData.Id === 0)                                  //新用户注册
                    || (NewPwdMod <= 0 && $("input[name='NewPassword']").val().length > 0)) { //或修改用户密码
                    notice.error("密码长度超出限定范围");
                    return false;
                }
                postData.SelectedRoleIds = userRoleSelecter.getValue('value');
                if (postData.SelectedRoleIds.length <= 0) {
                    notice.error("未分配用户关联角色");
                    userRoleSelecter.warning('#e54d42', true);
                    return false;
                }
                //else {
                //    //delete postData.checkBoxtext;
                //    postData.SelectedRoleIds = [];
                //    $("input[name='checkBoxtext']").each(function () {
                //        postData.SelectedRoleIds.push($(this).val());
                //    });
                //}
                var index = layer.load(2, {time: 10*1000});
                httpapi.fetchPost('/api/system/adminusermanage/accountedit', postData).then(res => {
                    layer.close(index);
                    if (!httpapi.checkResponse(res))
                        //输入信息校验错误
                        notice.error(res.message);
                    else {//Success
                        if (postData.Id == 0) {
                            notice.success(res.message);
                            Util.CloseMainWindow();
                        } else {
                            layer.confirm(res.message, function () {
                                Util.CloseMainWindow();
                            }, function () {
                                window.location.reload();
                            });
                        }
                    }
                }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
        });
    </script>
}